package com.xmut.xmutbackend.controller;

import com.xmut.xmutbackend.entity.Dept;
import com.xmut.xmutbackend.entity.Result;
import com.xmut.xmutbackend.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 部门表 前端控制器
 * </p>
 *
 * @author 李俊煌
 * @since 2025-06-10
 */
@RestController
@RequestMapping("/depts")
public class DeptController {
    @Autowired
    private IDeptService deptService;

    //请求部门数据
    @GetMapping
    public Result<List> findAll () {
        List<Dept> depts = deptService.list();
        return Result.success(depts);
    }

    // 新增部门
    @PostMapping
    public Result<Dept> add(@RequestBody Dept dept){
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        dept.setCreateTime(now);
        dept.setUpdateTime(now);

        // 保存部门
        deptService.save(dept);
        return Result.success(dept);
    }

    // 根据ID查询部门
    @GetMapping("/{id}")
    public Result<Dept> getById(@PathVariable Long id) {
        Dept dept = deptService.getById(id);
        if(dept == null) {
            return Result.fail("部门不存在");
        }
        return Result.success(dept);
    }

    // 更新部门
    @PutMapping
    public Result<Dept> update(@RequestBody Dept dept){
        dept.setUpdateTime(LocalDateTime.now());
        deptService.updateById(dept);
        return Result.success(dept);
    }

    // 根据ID删除部门
    @DeleteMapping("/{id}")
    public Result<String> deleteById (@PathVariable Integer id){
        // 删除部门
        deptService.removeById(id);
        return Result.success("删除成功");
    }
}
